package com.powernode.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.apache.commons.lang3.time.DateUtils;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

/**
 * 创建token
 * 解析token
 */
//@Component
public class TokenUtil {

    /*秘钥字符串*/
//    @Value("${token.secretKey}")
    private String key;

    public TokenUtil(String key) {
        this.key = key;
    }

    public TokenUtil() {
    }

    /*创建token*/
    public String createJwt(Map<String,Object> payLoad,int minute){
        /*秘钥*/
        SecretKey secretKey = Keys.hmacShaKeyFor(key.getBytes(StandardCharsets.UTF_8));
        /*创建token*/
        String jwt = Jwts.builder().signWith(secretKey, SignatureAlgorithm.HS256)
                .setExpiration(DateUtils.addMinutes(new Date(), minute))//过期时间
                .setIssuedAt(new Date())//颁发时间
                .setId(UUID.randomUUID().toString().replaceAll("-", ""))//token 的唯一标识
                .addClaims(payLoad)//负载数据
                .compact();
        return jwt;
    }

    /*解析token*/
    public Claims readJwt(String jwt){
        Claims claims =null;
        try {
            /*获取秘钥*/
            SecretKey secretKey = Keys.hmacShaKeyFor(key.getBytes(StandardCharsets.UTF_8));
            claims = Jwts.parserBuilder().setSigningKey(secretKey).build().parseClaimsJws(jwt).getBody();
        }catch (Exception e){
            e.printStackTrace();
        }
        return claims;
    }
}
